#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys,json,logging
import numpy as np
sys.path.append("../cow")


from flask import Flask, render_template,jsonify
from flask import request
from flask_socketio import SocketIO, emit
from flask.json import JSONEncoder
from database import con
from api import app
import importlib


app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app,async_mode='threading')

def log(msg):
    socketio.emit(
        'log', {
            "code":1,
            "data":msg
        }
    )

@app.route('/')
def index():
    return render_template('index.html')



# @app.route('/select',methods=['GET', 'POST'])
# def select():
    
#     try:
#         data = request_parse(request)
#         sql = data["sql"]
#         cur = con.cursor()
#         cur.execute(sql)
#         result = cur.fetchall()
#         return {
#             "code":0,
#             "data":result 
#         }
#     except  Exception as e:
#         print(e)
#         return {
#             "code":-1,
#             "msg":str(e)
#         }
#     finally:
#         cur.close()

# @app.route('/update',methods=['GET', 'POST'])
# def update():
#     try:
#         data = request_parse(request)
#         sql = data["sql"]
#         cur = con.cursor()
#         cur.execute(sql)
#         result={"count":cur.rowcount}
#         con.commit()
#         return {
#             "code":0,
#             "data":result 
#         }
#     except  Exception as e:
#         print(e)
#         return {
#             "code":-1,
#             "msg":str(e)
#         }
#     finally:
#         cur.close()
    

############# base  http ##################
@app.route('/store/basic')
def store_basic():
    # 获取股票列表
    try:
        from Tusharedata import db
        data = request_parse(request)
        keyword = data["keyword"] 
        changeTime = data["changeTime"]
        bases = db.StockBasic().fitter(keyword=keyword,changeTime=changeTime)
        return {
            "code":0,
            "data":bases 
        }
    except  Exception as e:
        print(e)
        return {
            "code":-1,
            "msg":"error" 
        }

@app.route('/etf/basic')
def etf_basic():
    # 获取etf列表
    from Tusharedata import db
    data = request_parse(request)
    keyword = data["keyword"]
    changeTime = data["changeTime"]
    bases = db.StockBasic().fitter(keyword=keyword,changeTime=changeTime)
    return {
        "code":0,
        "data":bases 
    }


############# scheme 策略 http ##################
@app.route('/scheme')
def scheme():
    from Analyse import analyses
    analyses = analyses()
    return {
        "code":0,
        "data":analyses 
    }

@app.route('/analyses/history')
def analysesHistory():
    # 获取回测历史记录
    from Analyse.catch import AnalyseCache
    data = request_parse(request) 
    history = AnalyseCache().search(name=data["name"])
    
    return {
        "code":0,
        "data":history
    }


@app.route('/analyses/history/Details')
def analysesHistoryDetails():
    # 获取历史回测详细信息
    from Analyse.catch import AnalyseBSRecords
    from Analyse.catch import AnalyseZoneRecords
    data = request_parse(request) 
    bsRecord = AnalyseBSRecords().search(cache_id=data["cacheId"])
    zone = AnalyseZoneRecords().search(cache_id=data["cacheId"])
    return {
        "code":0,
        "data":{
            "bsRecord":bsRecord,
            "zone":zone
            }
    }


#############  ##################
@app.route('/share/daily')
def shareDaily():
    try:
        #获取股票历史记录
        from Tusharedata.daily import load
        data = request_parse(request) 
        df = load(data["code"])
      
        # if(data["date"]!= None):
        #     df = df[df["date"]>data["date"]]
        df = df.where(df.notnull(), None)
        dailys = df.to_dict(orient="records")
        return {
            "code":0,
            "data":dailys
        }
    except  Exception as e:
        print(e)
        return {
            "code":-1,
            "msg":str(e) 
        }

@socketio.on('message')
def handle_message(message):
    socketio.emit('my response', message)
 
@socketio.on('analyse')
def handle_my_custom_event(data):
    rjson = json.loads( str(data, 'utf-8'))
    analyse = importlib.import_module("Analyse."+rjson["name"])
    
    analyse.log = log
    analyse.setup()
    socketio.emit(
        'analyse', {
            "code":0,
            "data":"end"
        }
    )

@socketio.on('analyse1')
def handle_my_custom_event(data):
    from Analyse import Analyse
    param = json.loads(data)

    analyse = Analyse(param["name"])
    analyse.setup(
        begin=param["begin"],
        end=param["end"],
        codes=param["codes"],
        parameter=param["parameter"],
        )
  
def request_parse(req_data):
    '''解析请求数据并以json形式返回'''
    if req_data.method == 'POST':
        data = req_data.json
    elif req_data.method == 'GET':
        data = req_data.args
    return data


from api import scheme
app.register_blueprint(scheme)

if __name__ == '__main__':
    socketio.run(app, host='0.0.0.0',port=5000, log_output=True)
